import 'package:cbec_app/components/base/base_image.dart';
import 'package:cbec_app/components/base/base_interactive.dart';
import 'package:cbec_app/components/base/base_page.dart';
import 'package:cbec_app/components/base/base_nav_bar.dart';
import 'package:cbec_app/components/common/common_style.dart';
import 'package:cbec_app/pages/member/controller/member_ctr.dart';
import 'package:cbec_app/routes/routes.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../../utils/EventMgr.dart';
import '../../main/controller/main_ctr.dart';

//VIP中心
class MyVip extends GetView<MemberController> {
  const MyVip({super.key});

  @override
  Widget build(BuildContext context) {
    return GetBuilder<MemberController>(builder: (controller) {
      return BasePage(
        title: "VIP卡",
        iconType: IconType.back,
        children: [
          controller.vipInfo.isNotEmpty
              ? Container(
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(10),
                    gradient: LinearGradient(
                      colors: [
                        Tools.fromHex("#E2E8EC"),
                        Tools.fromHex("#B9C7D3"),
                      ],
                    ),
                  ),
                  margin: EdgeInsets.fromLTRB(18.w, 10.w, 18.w, 0.w),
                  height: 145.h,
                  child: Stack(
                    children: [
                      Positioned(
                          top: 0,
                          right: 0,
                          child: ClipPath(
                            clipper: TrapezoidClipper(),
                            child: Container(
                              width: 115.w,
                              height: 32.5.h,
                              decoration: BoxDecoration(
                                  borderRadius: const BorderRadius.only(
                                    topRight: Radius.circular(10.0),
                                  ),
                                  color: Tools.fromHex("#435970")),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [Text("我的积分", style: TextStyle(fontSize: 12, fontWeight: FontWeight.w400, color: Tools.fromHex("#999999"))), Text(controller.vipInfo['points'].toString(), style: TextStyle(fontSize: 12, fontWeight: FontWeight.w500, color: Tools.fromHex("#FFFFFF")))],
                              ),
                            ),
                          )),
                      Positioned(
                          child: Container(
                              padding: EdgeInsets.only(top: 37.w, left: 8.w),
                              child: Column(
                                children: [
                                  Row(
                                    children: [
                                      BaseImage(url: "vip_icon.png", width: 20, height: 20),
                                      SizedBox(
                                        width: 4.w,
                                      ),
                                      Text(controller.vipInfo['levelName'] ?? '', style: const TextStyle(fontWeight: FontWeight.w500, fontSize: 15)),
                                    ],
                                  ),
                                  Container(
                                    margin: EdgeInsets.only(top: 10.w, bottom: 10.w),
                                    padding: EdgeInsets.only(right: 8.w),
                                    child: LinearProgressIndicator(
                                      value: controller.vipInfo['nextGrowthValue'] > 0 ? double.parse((controller.vipInfo['growthValue'] / controller.vipInfo['nextGrowthValue']).toStringAsFixed(2)) : 0,
                                      backgroundColor: Tools.fromHex("#DDE6F5"),
                                      valueColor: AlwaysStoppedAnimation<Color>(Tools.fromHex("#2D4255")),
                                    ),
                                  ),
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    children: [
                                      const Text(
                                        "成长值",
                                        style: TextStyle(fontWeight: FontWeight.w400, fontSize: 12),
                                      ),
                                      Text(
                                        "${controller.vipInfo['growthValue'] ?? ''.toString()}/${controller.vipInfo['nextGrowthValue'] ?? ''.toString()}",
                                        style: const TextStyle(fontWeight: FontWeight.w700, fontSize: 14),
                                      ),
                                      SizedBox(width: 10.w),
                                      Expanded(
                                        // 或者用 Flexible
                                        child: Text(
                                          controller.vipInfo['growthText'] ?? '',
                                          style: const TextStyle(
                                            fontWeight: FontWeight.w700,
                                            fontSize: 12,
                                            overflow: TextOverflow.ellipsis,
                                          ),
                                          maxLines: 2, // 限制显示的行数
                                        ),
                                      ),
                                    ],
                                  ),
                                  SizedBox(height: 21.w),
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    crossAxisAlignment: CrossAxisAlignment.center,
                                    children: [
                                      BaseInteractive(
                                        onClick: () => {controller.scoreLog()},
                                        childWidget: Text("积分明细", style: TextStyle(fontSize: 12, fontWeight: FontWeight.w400, color: Tools.fromHex("#4D87FF"))),
                                      ),
                                      Container(
                                        margin: EdgeInsets.only(right: 9.w),
                                        child: BaseInteractive(
                                          onClick: () => {controller.alterQrCode(context)},
                                          childWidget: BaseImage(url: "vip_code.png", width: 18, height: 18),
                                        ),
                                      )
                                    ],
                                  )
                                ],
                              ))),
                    ],
                  ),
                )
              : emptyWidget(),

          //任务
          Container(
            margin: EdgeInsets.fromLTRB(18.w, 20.w, 18.w, 0.w),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  "基础任务",
                  style: setTextStyle(15, FontWeight.w500, Tools.fromHex("#333333")),
                ),
                SizedBox(height: 10.w),
                Container(
                    decoration: border_radis(Colors.white),
                    child: Column(
                      children: [for (var item in controller.taskList) item['code'] == 'bindMobile' || item['code'] == 'authRealName' ? TaskItem(item: item) : emptyWidget()],
                    ))
              ],
            ),
          ),

          //任务
          Container(
            margin: EdgeInsets.fromLTRB(18.w, 20.w, 18.w, 0.w),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  "购物任务",
                  style: setTextStyle(15, FontWeight.w500, Tools.fromHex("#333333")),
                ),
                SizedBox(height: 10.w),
                Container(
                    decoration: border_radis(Colors.white),
                    child: Column(
                      children: [for (var item in controller.taskList) item['code'] == 'buyGoods' || item['code'] == 'placeOrder' ? TaskItem(item: item) : emptyWidget()],
                    ))
              ],
            ),
          ),
        ],
      );
    });
  }
}

class TaskItem extends StatelessWidget {
  final Map item;

  const TaskItem({
    super.key,
    required this.item,
  });

  @override
  Widget build(BuildContext context) {
    String _imageUrl;
    String _router;
    switch (item['code']) {
      case "bindMobile":
        _imageUrl = "task_bind.png";
        _router = Routes.fixPhone;
        break;
      case "authRealName":
        _imageUrl = "task_auth.png";
        _router = Routes.userInfo;
        break;
      case "buyGoods":
        _imageUrl = "task_buy.png";
        _router = Routes.main;
        break;
      case "placeOrder":
        _imageUrl = "task_order.png";
        _router = Routes.main;
        break;

      default:
        _imageUrl = '';
        _router = "";
    }
    return Container(
      decoration: BoxDecoration(
        border: Border(
          bottom: BorderSide(color: Tools.fromHex("#F7F7F7"), width: 1.0), // 设置灰色下边框
        ),
      ),
      padding: EdgeInsets.all(10.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          //左侧图片及文本
          Row(
            children: [
              BaseImage(url: _imageUrl, width: 24.w, height: 24.w),
              SizedBox(width: 10.w),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(item['name'] ?? '', style: setTextStyle(14, FontWeight.w500, Tools.fromHex("#333333"))),
                  SizedBox(height: 5.w),
                  item['tab'] == 0
                      ?
                      //基本任务
                      Text("${item['needValueUnitJson'][0] ?? ''}${item['growthValue'] ?? ''}成长值", style: setTextStyle(12, FontWeight.w300, Tools.fromHex("#999999")))
                      :
                      //成长任务
                      Text("${item['needValueUnitJson'][0] ?? ''}${item['needValue']}${item['needValueUnitJson'][1] ?? ''}${item['growthValue'] ?? ''}成长值", style: setTextStyle(12, FontWeight.w300, Tools.fromHex("#999999")))
                ],
              )
            ],
          ),
          //右侧按钮
          solidButton(item['isFinished'] == false ? "去完成" : "已完成", textColor: Tools.fromHex(item['isFinished'] == false ? "#F83F2D" : "#999999"), backgroundColor: Colors.white, fontsize: 12, width: 50.w, height: 25.w, borderColor: Tools.fromHex("#999999"), () {
            if (item['isFinished'] == false) {
              switch (_router) {
                case Routes.main:
                  Get.until((route) => Get.currentRoute == _router);
                  EventMgr.send(EventType.exchangeNav, MainController.mainBottomNavRouteNameHome);
                  break;
                case Routes.userInfo:
                  Get.until((route) => Get.currentRoute == _router);
                  EventMgr.send(EventType.exchangeNav, MainController.mainBottomNavRouteNameMy);
                  break;
                default:
                  Get.offAllNamed(_router);
                  break;
              }
            }
          }),
        ],
      ),
    );
  }
}

class TrapezoidClipper extends CustomClipper<Path> {
  @override
  Path getClip(Size size) {
    Path path = Path();
    path.lineTo(size.width, 0.0);
    path.lineTo(size.width, size.height);
    path.lineTo(20, size.height); // 调整斜边的高度
    path.close();
    return path;
  }

  @override
  bool shouldReclip(CustomClipper<Path> oldClipper) {
    return false;
  }
}
